package com.timebank.volunteer.service.impl;

import com.timebank.volunteer.service.VolunteerNotice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 志愿服务 通知 实现类
 * @author shiliuyinzhen
 */
@Service
@Slf4j
public class VolunteerNoticeImpl implements VolunteerNotice {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 订阅通知
     * @param volunteerId
     * @param userId
     * @return
     */
    @Override
    public Boolean subscribe(Long volunteerId, Long userId) {
        //创建rabbit管理器
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        //创建direct类型交换机
        DirectExchange exchange = new DirectExchange("volunteer_notice");
        //创建对应用户的队列,设置可持久化，命名规则为： volunteer_subscribe + 志愿服务Id
        Queue queue = new Queue("volunteer_service_" + volunteerId,true);
        //绑定交换机和队列,路由key为：volunteer.volunteerId
        String routingKey = "volunteer.service." + volunteerId;
        Binding binding = BindingBuilder
                .bind(queue)
                .to(exchange)
                .with(routingKey);
        //声明交换机,队列，绑定
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareBinding(binding);
        log.info("绑定成功：【交换机：{}，队列：{}，路由key:{}】",exchange,queue,routingKey);
        return true;
    }
}
